<template>
  <div
    class="orderlist kw-bottotm custom-loading-svg"
    v-loading="getlutianorderloading"
    element-loading-text="正在获取数据中..."
    :element-loading-svg="svg"
    element-loading-svg-view-box="-10, -10, 50, 50"
  >
    <div class="orderlist-header">
      <!-- <div class="orderlist-title">订单列表</div> -->
      <div class="orderlist-buttons">
        <el-form
          :inline="true"
          :model="keywordsform"
          class="demo-form-inline orderlist-keywords-form"
        >
          <el-form-item label="账号">
            <el-select
              v-model="keywordsform.accountid"
              clearable
              placeholder="选择账号"
              @change="changeAccount(1)"
              class="orseruserid-selectinput"
              popper-class="orseruserid-select"
              style="width: 170px"
            >
              <el-option
                v-for="item in accountselect"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="keywordsform.type"
              placeholder="选择类型"
              class="orseruserid-selectinput"
              @change="changeAccount(1)"
              popper-class="orseruserid-select"
              style="width: 170px"
            >
              <el-option label="待確認" :value="1" />
              <el-option label="總覽" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="changeAccount(2)">更新</el-button>
            <el-button type="primary" @click="wipecacheGetdata()"
              >清空所选账号缓存重新获取</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="orderlist-progress" v-if="progressshow">
        <div class="orderlist-progress-label" v-if="orderpercentage != 100">
          正在获取中:
        </div>
        <div
          class="orderlist-progress-label"
          style="color: red"
          v-if="orderpercentage == 100"
        >
          获取完成:
        </div>
        <div style="flex: 1; margin-left: 20px">
          <el-progress :percentage="orderpercentage" :stroke-width="8" striped>
            <div>{{ orderpercentagetext }}</div>
          </el-progress>
        </div>
      </div>
    </div>

    <div class="orderlist-content" style="height: 70%">
      <el-table
        :data="lutianorderlist"
        class="orderlisttabel"
        :expand-row-keys="expandRowKeys"
        :row-key="(row) => row.index"
        @expand-change="handleExpandChange"
        style="width: 100%; height: 100%; font-size: 12px"
        :row-style="orderListrowStyle"
        border
      >
        <el-table-column type="expand">
          <template #default="props">
            <div class="orderlist-expand">
              <div
                class="orderlist-expand-item"
                v-for="(value, key) in orderexpandHtml(props.row)"
                :key="key"
              >
                <!-- <div>{{key}}</div> -->
                <div class="orderlist-expand-item-title">
                  <span>{{ orderMap[key] }}：</span>
                </div>

                <div class="orderlist-expand-item-text">
                  <div v-if="orderMap[key] === '商品主图'">
                    <!-- <el-image
                      :src="imgurls(value)"
                      :preview-src-list="previewSrcList"
                      :initial-index="0"
                      style="width: 80px; cursor: pointer"
                    /> -->
                    <!-- <div @paste="handlePaste"> -->

                    <el-input
                      style="
                        width: 146px;
                        margin-bottom: 6px;
                        height: 20px;
                        font-size: 11px;
                      "
                      type="text"
                      placeholder="点击粘贴上传图片"
                      @paste="handlePaste"
                    />

                    <el-upload
                      v-if="value == ''"
                      drag
                      action="http://47.99.66.117:5500/api/upload"
                      list-type="picture-card"
                      :show-file-list="false"
                      class="matchingaddupload"
                      :before-upload="beforeFileUpload"
                      :on-success="getuploadimgsuccess"
                    >
                      <el-icon
                        class="avatar-uploader-icon"
                        style="width: 100%; height: 100%"
                        ><Plus
                      /></el-icon>
                    </el-upload>
                    <!-- </div> -->

                    <div class="active-uploadimgs" v-if="value != ''">
                      <img
                        :src="imgurls(value)"
                        class="avatar el-upload-list__item-thumbnail"
                        style="height: 148px;width: 150px;"
                      />
                      <el-icon
                        style="margin-left: 20px; cursor: pointer"
                        @click="props.row.goodsimg = ''"
                        ><delete
                      /></el-icon>
                    </div>
                  </div>

                  <div v-if="orderMap[key] === '其他'">
                    <div v-if="value.length == 0">
                      <el-button
                        type="success"
                        size="small"
                        @click="addother(value)"
                        >添加</el-button
                      >
                    </div>
                    <div v-else class="addexpressnum">
                      <div class="addexpressnum-inputs">
                        <div
                          v-for="(item2, index) in value"
                          :key="index"
                          style="
                            margin-bottom: 5px;
                            display: flex;
                            align-items: center;
                          "
                        >
                          <el-input
                            v-model="value[index].label"
                            style="width: 50%; font-size: 12px"
                            placeholder="请输入"
                          ></el-input>
                          <div>：</div>
                          <el-input
                            v-model="value[index].value"
                            style="width: 100%; font-size: 12px"
                            placeholder="请输入"
                          ></el-input>
                        </div>
                      </div>
                      <div class="addexpressnum-button">
                        <el-button
                          type="success"
                          size="small"
                          @click="addother(value)"
                          >添加</el-button
                        >
                      </div>
                    </div>
                  </div>

                  <div v-if="orderMap[key] === '颜色尺码'">
                    <div class="orderlist-expand-other">
                      <div
                        class="expand-other-item"
                        v-for="(item, index) in value"
                        :key="index"
                      >
                        <div style="margin-top: 2px; font-size: 12px">
                          {{ item }}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-if="orderMap[key] === '商品名称'">
                    <div class="orderlist-expand-other">
                      <div
                        class="expand-other-item"
                        v-for="(item, index) in value"
                        :key="index"
                      >
                        <div style="margin-top: 2px; font-size: 12px">
                          {{ item }}
                        </div>
                      </div>
                    </div>
                  </div>

                  <div v-if="orderMap[key] === '国内快递单号'">
                    <div v-if="value.length == 0">
                      <el-button
                        type="success"
                        size="small"
                        @click="addexpressNum(value)"
                        >添加</el-button
                      >
                    </div>
                    <div v-else class="addexpressnum">
                      <div class="addexpressnum-inputs">
                        <div
                          v-for="(item2, index) in value"
                          :key="index"
                          style="margin-bottom: 5px"
                        >
                          <el-input
                            v-model="value[index]"
                            style="width: 100%; font-size: 12px"
                            placeholder="请输入"
                          ></el-input>
                        </div>
                      </div>
                      <div class="addexpressnum-button">
                        <el-button
                          type="success"
                          size="small"
                          @click="addexpressNum(value)"
                          >添加</el-button
                        >
                      </div>
                    </div>
                  </div>

                  <div
                    v-if="
                      orderMap[key] === '出货日期' ||
                      orderMap[key] === '结账时间'
                    "
                    style="width: 100%; height: auto; word-wrap: break-word"
                  >
                    <el-date-picker
                      v-model="props.row[key]"
                      type="date"
                      placeholder="请选择"
                      style="width: 100%; font-size: 12px"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                    />
                  </div>
                  <div
                    v-if="
                      orderMap[key] != '其他' &&
                      orderMap[key] != '商品主图' &&
                      orderMap[key] != '颜色尺码' &&
                      orderMap[key] != '商品名称' &&
                      orderMap[key] != '国内快递单号' &&
                      orderMap[key] != '拍货日期' &&
                      orderMap[key] != '出货日期' &&
                      orderMap[key] != '结账时间'
                    "
                    style="width: 100%; height: auto; word-wrap: break-word"
                  >
                    <el-input
                      v-model="props.row[key]"
                      style="width: 100%; font-size: 12px"
                      placeholder="请输入"
                      clearable
                    />
                  </div>
                </div>
              </div>
            </div>

            <div class="orderlist-button">
              <el-button
                type="primary"
                style="width: 20%"
                @click="submitaddorder(props.row)"
                >提交</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="orderStutas" label="状态" width="120">
          <template #default="scope">
            <el-select
              v-model="scope.row.orderStutas"
              style="font-size: 12px"
              placeholder="Select"
              @change="changeorderStutas(scope.row)"
            >
              <el-option
                v-for="item in orderStutasSelect"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="ordernumber"
          label="訂單編號"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="checkoutTime"
          label="结账时间"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="recipients"
          label="收件人"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column label="商品名称">
          <template #default="scope">
            <div style="padding: 0; margin: 0">
              <div
                v-for="(item, index) in scope.row.goodsName"
                :key="index"
                :style="`${
                  index + 1 == scope.row.goodsName.length
                    ? ''
                    : 'border-bottom: 1px solid #606266;'
                }`"
              >
                <div>
                  <p>{{ item }}</p>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格">
          <template #default="scope">
            <div>
              <div v-for="(item, index) in scope.row.colorSize" :key="index">
                <p>{{ item }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量" width="50" />
        <el-table-column
          prop="freight"
          width="50"
          label="运费"
          show-overflow-tooltip
        />
        <el-table-column prop="closingAmount" label="結帳總金額" width="100" />
        <el-table-column prop="logistics" label="物流方式" width="100" />
        <!-- <el-table-column
          fixed="right"
          label="操作"
          width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="changeorder(scope.row)"
            >
              修改
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click="clickdeleteorder(scope.row.goodsId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column> -->
      </el-table>
    </div>
    <div class="orderlist-footer">
      <el-pagination
        v-model:current-page="lutianorderlistcurrentpage"
        v-model:page-size="lutianorderlistpagesize"
        :small="small"
        :disabled="disabled"
        hide-on-single-page="true"
        background="true"
        class="paginationaddorderlist"
        prev-text="上一页"
        next-text="下一页"
        layout="prev, pager, next"
        :total="lutianorderlisttotal"
        @current-change="handleCurrentChange"
      />
    </div>

    <div style="display: none" ref="htmlContainer" v-html="htmlContent"></div>
  </div>
</template>
    
    <script setup lang="ts">
import { ref, reactive, onMounted, inject } from "vue";
import { useSaveApi } from "@/api/user/index.ts";
import axios from "axios";
import {
  addordergoods,
  saveOrderlist,
  deleteOrder,
  changeordergoods,
  saveAllOrderlist,
} from "@/api/order/index.ts";
import { saveAllAccountlist } from "@/api/account/index.ts";
import { saveCookielist } from "@/api/lutiancookie/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";

import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute } from "@/api/main.js";
import type {
  UploadFile,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadFiles,
  FormInstance,
  FormRules,
} from "element-plus";

import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

const activeuser = ref<any>({});
const keywordsform = ref({
  accountid: "",
  type: 1,
});
const accountselect = ref([]);

const htmlContent = ref("");
const htmlContainer = ref(null);

const activecookie = ref("");
const lutianorderlist = ref([]);
const lutianorderlisttotal = ref(0);
const lutianorderlistpagesize = ref(30);
const lutianorderlistcurrentpage = ref(1);

const logisticsSelect = ref([
  {
    value: "seven",
    label: "7-11 取貨付款服務",
  },
  {
    value: "self_seven",
    label: "(賣家提供)7-11取貨付款服務",
  },
  {
    value: "cvs",
    label: "全家、OK、萊爾富取貨付款服務",
  },
  {
    value: "oldtcat",
    label: "宅急便「黑貓 PAY 貨到付款」服務",
  },
  {
    value: "tcat",
    label: "黑貓宅急便服務",
  },
  {
    value: "maple",
    label: "便利帶隔日配服務",
  },
  {
    value: "postibox",
    label: "ｉ郵箱服務",
  },
  {
    value: "famimart",
    label: "全家取貨服務",
  },
  {
    value: "self_fami",
    label: "(賣家提供)全家取貨付款服務",
  },
  {
    value: "hilife",
    label: "萊爾富取貨服務",
  },
  {
    value: "self_hilife",
    label: "(賣家提供)萊爾富取貨付款服務",
  },
]);

const getlutianorderloading = ref(false);
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;

const orderStutasSelect = ref([
  {
    value: 1,
    label: "待处理",
  },
  {
    value: 2,
    label: "有问题",
  },
  {
    value: 3,
    label: "已处理",
  },
  {
    value: 4,
    label: "已出库",
  },
]);
const orderMap = ref({
  buygoodsDate: "拍货日期",
  salespersonName: "销售员",
  storename: "店名",
  orderplatform: "接单平台",
  ordernumber: "订单编号",
  recipients: "收件人",
  address: "门市地址",
  colorSize: "颜色尺码",
  num: "数量",
  goodsimg: "商品主图",
  buygoodsUrl: "拍货链接",
  price: "售價（不含运费）",
  freight: "运费",
  priceFreight: "售价（含运费）",
  cost: "成本",
  closingAmount: "结账金额",
  checkoutTime: "结账时间",
  goodsName: "商品名称",
  phone: "电话",
  logistics: "物流方式",
  shippingDate: "出货日期",
  expressNum: "国内快递单号",
  expressCompanies: "快递公司",
  hsinchuNum: "新竹单号/超商",
  storeNum: "店号",
  collection: "代收（做拍货当天就完善）",
  productName: "品名",
  remarks: "备注",
  weight: "重量",
  other: "其他",
});

const expandRowKeys = ref([]);

const generateRowKey = ref([0]);

// 进度条
const progressshow = ref(false);
const orderpercentage = ref(0);
const orderpercentagetext = ref("");

const ordertrs = ref(0);

const getaccount = () => {
  accountselect.value = [];
  // 保存Cookie
  if (activeuser.value.isadmin == 1 || activeuser.value.isadmin == 2) {
    let data = {
      keyword: "",
    };
    saveAllAccountlist(data).then((res) => {
      console.log(res);
      if (res.code == 200) {
        res.data.forEach((item) => {
          let a = {
            value: item.id,
            label: item.account,
          };
          accountselect.value.push(a);
        });
      }
    });
  } else {
    if (activeuser.value.accounts != null && activeuser.value.accounts != "") {
      let accountsarr = activeuser.value.accounts.split(",");
      let accountsnamearr = activeuser.value.accountsname.split(",");

      for (let i = 0; i < accountsarr.length; i++) {
        let a = {
          value: accountsarr[i],
          label: accountsnamearr[i],
        };
        accountselect.value.push(a);
      }
    }
  }
};

const changeAccount = (stutas) => {
  if (keywordsform.value.accountid != "") {
    orderpercentage.value = 0;
    orderpercentagetext.value = "";
    ordertrs.value = 0;
    let data = {
      accountid: keywordsform.value.accountid,
      userId: activeuser.value.userId,
    };

    saveCookielist(data).then((res) => {
      if (res.code == 200) {
        if (res.data.length > 0 && res.data[0].cookie != null) {
          let cookie = res.data[0].cookie;
          activecookie.value = cookie;
          // lutianorderlist.value = [];
          lutianorderlistcurrentpage.value = 1;
          ipc
            .invoke(ipcApiRoute.getlutianorderlist, {
              cookie: cookie,
              lutianorderlistcurrentpage: lutianorderlistcurrentpage.value,
              userId: activeuser.value.userId,
              accountId: keywordsform.value.accountid,
              type: keywordsform.value.type,
              stutas: stutas,
            })
            .then(async (r) => {
              console.log(r);

              if (r.code == 1) {
                console.log(r.data);
                lutianorderlisttotal.value = r.total;
                lutianorderlist.value = r.data;
                htmlContent.value = "";
                progressshow.value = false;
              } else {
                if (r.data == "ECONNREFUSED") {
                  ElMessage({
                    message: "代理地址错误，请核实修改之后再次运行",
                    type: "warning",
                  });

                  return;
                }
                console.log(r);

                htmlContent.value = removeEscapedCharacters(r.data);
                // console.log(r);

                setTimeout(() => {
                  const logincard =
                    htmlContainer.value.querySelector(".login-card");
                  const loginwrap =
                    htmlContainer.value.querySelector(".login-wrap");
                  if (logincard != null || loginwrap != null) {
                    ElMessage({
                      message: "所选账号登录已过期，请重新登录",
                      type: "warning",
                    });
                    htmlContent.value = "";
                    activecookie.value = "";
                    getlutianorderloading.value = false;
                    lutianorderlisttotal.value = 0;
                    lutianorderlist.value = [];
                    htmlContent.value = "";
                    progressshow.value = false;
                  } else {
                    const regex = /\\"total\\":\s*(\d+)/;
                    const match = r.data.match(regex);
                    console.log(match);

                    if (match && match.length > 0) {
                      lutianorderlisttotal.value = parseFloat(match[1]);
                      let trids = [];
                      if (keywordsform.value.type == 1) {
                        let trs = htmlContainer.value.querySelectorAll(
                          ".mybid-table tbody tr .col-user"
                        );
                        trs.forEach((item) => {
                          trids.push(
                            item.childNodes[0].data.replace(/\s/g, "")
                          );
                        });
                      } else {
                        let trs = htmlContainer.value.querySelectorAll(
                          ".mybid-table tbody tr"
                        );
                        trs.forEach((item) => {
                          let href =
                            item.querySelector(".bk12") == null
                              ? ""
                              : item.querySelector(".bk12").href;
                          if (href == "") {
                            trids.push("");
                          } else {
                            let match = href.match(/tno=(\d+)/);

                            if (match) {
                              trids.push(match[1]);
                            } else {
                              trids.push("");
                            }
                          }
                        });
                      }

                      if (trids.length > 0) {
                        if (r.code == 3) {
                          console.log(trids);
                          console.log(r.oneordernumber);
                          let idindex = trids.indexOf(r.oneordernumber);
                          if (idindex !== -1) {
                            // 使用 slice 方法截取从数组开头到特定值索引之前的部分
                            let slicedArray = trids.slice(0, idindex);
                            console.log(slicedArray);
                            if (slicedArray.length > 0) {
                              lutianorderlist.value = [];
                              recugetorderdetail(0, slicedArray, 1);
                            } else {
                              htmlContent.value = "";
                              console.log(lutianorderlist.value);
                              getlutianorderloading.value = false;
                              ElMessage({
                                message: "数据获取完毕",
                                type: "success",
                              });
                            }
                          } else {
                            progressshow.value = true;
                            ordertrs.value = trids.length;
                            console.log(trids);
                            lutianorderlist.value = [];
                            recugetorderdetail(0, trids, 1);
                          }
                        } else {
                          progressshow.value = true;
                          ordertrs.value = trids.length;
                          // console.log(trids);
                          lutianorderlist.value = [];
                          recugetorderdetail(0, trids, 0);
                        }
                      } else {
                        ElMessage({
                          message: "所选账号暂无订单",
                          type: "warning",
                        });
                        lutianorderlisttotal.value = 0;
                        lutianorderlist.value = [];
                        htmlContent.value = "";
                        progressshow.value = false;
                      }
                    } else {
                      ElMessage({
                        message: "错误请重试",
                        type: "warning",
                      });
                      htmlContent.value = "";
                    }
                  }
                }, 100);
              }
            });
        } else {
          ElMessage({
            message: "所选账号还未保存cookie，请登录",
            type: "warning",
          });
          activecookie.value = "";
          getlutianorderloading.value = false;
          lutianorderlisttotal.value = 0;
          lutianorderlist.value = [];
          htmlContent.value = "";
          progressshow.value = false;
        }
      }
    });
  }
};

// 清空所选账号缓存重新获取
const wipecacheGetdata = () => {
  if (keywordsform.value.accountid != "") {
    let data = {
      accountid: keywordsform.value.accountid,
      userId: activeuser.value.userId,
    };
    console.log(data);

    ipc
      .invoke(ipcApiRoute.wipecache, {
        accountId: keywordsform.value.accountid,
        userId: activeuser.value.userId,
        type: keywordsform.value.type,
      })
      .then(async (r) => {
        console.log(r);
        if (r.code == 200) {
          lutianorderlist.value = [];
          lutianorderlisttotal.value = 0;
          changeAccount(1);
        }
      });
  }
};

// nums2 1:从头部添加内容 0：全部添加 3:尾部添加
const recugetorderdetail = (num, ids, nums2) => {
  if (num + 1 <= ids.length) {
    let gno = ids[num];
    console.log(gno);

    ipc
      .invoke(ipcApiRoute.getlutianorderdetail, {
        cookie: activecookie.value,
        gno: gno,
      })
      .then(async (r) => {
        // console.log(r);
        htmlContent.value = removeEscapedCharacters(r);
        setTimeout(() => {
          let resultObject = accountselect.value.find(
            (obj) => obj.value === keywordsform.value.accountid
          );
          let price = htmlContainer.value.querySelector(
            ".transaction-fee-list-wrap .item-price-symbol"
          )
            ? htmlContainer.value.querySelector(
                ".transaction-fee-list-wrap .item-price-symbol"
              ).innerText
            : 0;

          console.log(price);
          if (price == 0) {
            htmlContainer.value.querySelectorAll(
              ".transaction-fee-list-wrap .item-price-symbol"
            );
          }

          let price2 = price != 0 ? parseFloat(price.replace(/,/g, "")) : 0;
          let priceFreight = htmlContainer.value.querySelector(
            ".rt-text-xx-large"
          )
            ? htmlContainer.value.querySelector(".rt-text-xx-large").innerText
            : 0;
          let priceFreight2 =
            priceFreight != 0 ? parseFloat(priceFreight.replace(/,/g, "")) : 0;
          // getyearmounthday()

          const regex = /\\"deliveryType\\":\\"([^"]+)\\"/;
          const match = r.match(regex);
          console.log(match);

          // 物流方式
          let logisticsstr = "";
          if (match && match.length > 0) {
            logisticsSelect.value.forEach((item) => {
              if (item.value == match[1]) {
                logisticsstr = item.label;
              }
            });
          }

          let data = {
            index: num + 1,
            orderStutas: 1,
            buygoodsDate: "",
            salespersonName: activeuser.value.name,
            storename: resultObject.label,
            orderplatform: "露天平台",
            ordernumber: screenorderData(
              "transaction-order-info-item",
              "order-info-item-label",
              "order-info-item-content",
              "訂單編號"
            ),
            recipients: screenorderData(
              "rt-list-item",
              "transaction-section-main-item-label",
              "transaction-section-main-item-content",
              "收件人"
            ),
            address: screenorderData(
              "rt-list-item",
              "transaction-section-main-item-label",
              "transaction-section-main-item-content",
              "門市 / 地址"
            ),
            colorSize: getcolorSize(),
            num: htmlContainer.value.querySelector(".fee-list-item-label")
              ? htmlContainer.value
                  .querySelector(".fee-list-item-label")
                  .innerText.match(/\d+/)[0]
              : "",
            goodsimg: "",
            buygoodsUrl: "",
            price: price2,
            freight: priceFreight2 - price2,
            priceFreight: priceFreight2,
            cost: "",
            closingAmount: priceFreight2,
            checkoutTime: screenorderData(
              "transaction-order-info-item",
              "order-info-item-label",
              "order-info-item-content",
              "結帳時間"
            ).replace(/\//g, "-"),
            goodsName: getgoodsName(),
            phone: screenorderData(
              "rt-list-item",
              "transaction-section-main-item-label",
              "transaction-section-main-item-content",
              "手機"
            ),
            logistics: logisticsstr,
            shippingDate: "",
            expressNum: [],
            expressCompanies: "",
            hsinchuNum: "",
            storeNum: "",
            collection: "",
            productName: "",
            remarks: "",
            weight: "",

            other: [],
          };

          lutianorderlist.value.push(data);
          let numi = num + 1;
          recugetorderdetail(numi, ids, nums2);

          orderpercentagetext.value = `${numi}/${ordertrs.value}`;
          orderpercentage.value = (numi / ordertrs.value) * 100;
        }, 100);
      });
  } else {
    htmlContent.value = "";
    console.log(lutianorderlist.value);
    getlutianorderloading.value = false;
    ElMessage({
      message: "数据获取完毕",
      type: "success",
    });

    let a = {
      userId: activeuser.value.userId,
      accountId: keywordsform.value.accountid,
      page: lutianorderlistcurrentpage.value,
      total: lutianorderlisttotal.value,
      data: lutianorderlist.value,
      type: keywordsform.value.type,
      nums2: nums2,
    };
    ipc
      .invoke(ipcApiRoute.savesqlitdata, {
        data: JSON.stringify(a),
      })
      .then(async (r) => {
        console.log(r);
        lutianorderlist.value = r.data;
      });
  }
};

const removeEscapedCharacters = (str) => {
  // 定义正则表达式匹配转义字符的模式
  const escapedCharsRegex = /\\[btnfr"'\\]/g;

  // 使用 replace 方法将匹配到的转义字符替换为空字符串
  return str.replace(escapedCharsRegex, "");
};

// 筛选订单数据
const screenorderData = (calss1, class2, class3, class2txt) => {
  let class1s = htmlContainer.value.querySelectorAll(`.${calss1}`);
  let htmlstr = "";

  class1s.forEach((item, index) => {
    if (
      item.querySelector(`.${class2}`) &&
      item.querySelector(`.${class2}`).innerText == class2txt
    ) {
      htmlstr = item.querySelector(`.${class3}`).innerText.replace(/\s/g, "");
    }
  });

  return htmlstr;
};

// 颜色尺码
const getcolorSize = () => {
  let trs = htmlContainer.value.querySelectorAll(".rt-table tbody tr");
  let colorsizearr = [];

  for (let i = 1; i < trs.length; i++) {
    if (trs[i].querySelector(".g-spec") != null) {
      let a = trs[i].querySelector(".g-spec").innerText;
      colorsizearr.push(a);
    } else {
      colorsizearr.push("");
    }
  }
  return colorsizearr;
};

// 商品名称
const getgoodsName = () => {
  let trs = htmlContainer.value.querySelectorAll(".rt-table tbody tr");
  let goodsNamearr = [];

  for (let i = 1; i < trs.length; i++) {
    let a = trs[i].querySelector(".col-goods-inner-item-main a").innerText;
    goodsNamearr.push(a);
  }
  return goodsNamearr;
};

// 返回年月日
const getyearmounthday = () => {
  let now = new Date();

  // 获取北京时间（东八区，北京时间是标准时间的8小时后）
  let beijingTime = new Date();

  // 获取年、月、日
  let year = beijingTime.getFullYear();
  let month = beijingTime.getMonth() + 1; // 月份是从0开始的，所以要加1
  let day = beijingTime.getDate();

  // 格式化年月日，保证单个数字有前导零（如月份和日期）
  let formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day
    .toString()
    .padStart(2, "0")}`;

  return formattedDate;
};

const imgurls = (goodsimg) => {
  if (goodsimg != "") {
    return `http://47.99.66.117:3307/imagest/${goodsimg}`;
  } else {
    return "";
  }
};

const handleExpandChange = (row, expandedRows) => {
  if (expandedRows.length > 0) {
    // 获取最新展开的行的索引
    const latestExpandedIndex = expandedRows[expandedRows.length - 1].index;

    // 更新 expandRowKeys，只保留最新展开的行的索引
    expandRowKeys.value = [latestExpandedIndex];
  } else {
    expandRowKeys.value = [];
  }
};

const orderexpandHtml = (row) => {
  if (Object.keys(row).length === 0) {
    return "";
  } else {
    const { index, buygoodsDate, orderStutas, ...filtered } = row;
    // console.log(filtered);

    return filtered;
  }
};

// 保存
const submitaddorder = (row) => {
  console.log(row);
  ElMessageBox.confirm("请确保当前信息已填写无误", "提示", {
    confirmButtonText: "继续",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let expressNumarr = row.expressNum.filter(
        (item) => item !== ""
      );
      let copyrow = JSON.parse(JSON.stringify(row));
      copyrow.colorSize = JSON.stringify(row.colorSize);
      copyrow.orderStutas = 1;
      copyrow.expressNum = JSON.stringify(expressNumarr);
      copyrow.goodsName = JSON.stringify(row.goodsName);
      copyrow.other = JSON.stringify(row.other);
      copyrow.createrTime = getformattedDate();
      copyrow.changeTime = getformattedDate();
      copyrow.buygoodsDate = getyearmounthday();
      copyrow.userId = activeuser.value.userId;
      delete copyrow.index;
      delete copyrow.orderStutas;
      if (row.expressNum.length > 1) {
        copyrow.specialtype = "1";
      } else {
        copyrow.specialtype = "0";
      }
      console.log(copyrow);

      addordergoods(copyrow).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "订单添加成功",
            type: "success",
          });
        } else {
          ElMessage({
            message: "订单添加失败",
            type: "warning",
            plain: true,
          });
        }
        changeorderStutas(row);
        // console.log(res);
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const getformattedDate = () => {
  let currentTimestamp = Date.now();

  // 将时间戳转换为Date对象
  let date = new Date(currentTimestamp);

  // 获取UTC时间的各个部分
  let year = date.getUTCFullYear();
  let month = date.getUTCMonth() + 1; // 月份从0开始，需要加1
  let day = date.getUTCDate();
  let hours = date.getUTCHours();
  let minutes = date.getUTCMinutes();
  let seconds = date.getUTCSeconds();

  // 北京时间是UTC+8
  hours += 8;
  // 调整小时和日期
  if (hours >= 24) {
    hours -= 24;
    day += 1;
    // 如果天数超过本月最大天数，需要调整月份和年份
    let daysInMonth = new Date(year, month, 0).getDate();
    if (day > daysInMonth) {
      day = 1;
      month += 1;
      if (month > 12) {
        month = 1;
        year += 1;
      }
    }
  }
  // 格式化日期和时间部分
  let formattedDate = `${year}-${String(month).padStart(2, "0")}-${String(
    day
  ).padStart(2, "0")} ${String(hours).padStart(2, "0")}:${String(
    minutes
  ).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;

  return formattedDate;
};

// 添加国内快递单号
const addexpressNum = (value) => {
  value.push("");
};

const addother = (value) => {
  let a = {
    label: "",
    value: "",
  };
  value.push(a);
};

const getuploadimgsuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  // console.log(response);
  if (response.code == 200) {
    ElMessage({
      message: "图片上传成功",
      type: "success",
    });

    lutianorderlist.value[expandRowKeys.value[0] - 1].goodsimg =
      response.data.url;
  }
};

const handlePaste = (event) => {
  const items = (event.clipboardData || event.originalEvent.clipboardData)
    .items;
  for (const item of items) {
    if (item.kind === "file") {
      const file = item.getAsFile();
      if (file) {
        // 可以在这里处理粘贴的文件，例如上传等操作
        console.log("Pasted file:", file);
        // 调用上传方法
        // handleUpload(file);
        uploadFile(file);
      }
    }
  }
};

const uploadFile = (file) => {
  const formData = new FormData();
  formData.append("file", file);

  // 发起上传请求
  // 这里假设使用 axios 进行上传
  axios
    .post("http://47.99.66.117:5500/api/upload", formData)
    .then((response) => {
      // console.log("Upload success:", response.data);
      if (response.data.code == 200) {
        ElMessage({
          message: "图片上传成功",
          type: "success",
        });

        lutianorderlist.value[expandRowKeys.value[0] - 1].goodsimg =
          response.data.data.url;
      }
      // 处理上传成功的逻辑
      // 可以将上传成功后的 URL 设置到 pasteImageUrl 中
      // pasteImageUrl.value = response.data.url;
    })
    .catch((error) => {
      console.error("Upload error:", error);
      // 处理上传失败的逻辑
    });
};

// 分页
const handleCurrentChange = () => {
  orderpercentage.value = 0;
  orderpercentagetext.value = "";
  ordertrs.value = 0;
  lutianorderlist.value = [];
  ipc
    .invoke(ipcApiRoute.getlutianorderlist, {
      cookie: activecookie.value,
      lutianorderlistcurrentpage: lutianorderlistcurrentpage.value,
      userId: activeuser.value.userId,
      accountId: keywordsform.value.accountid,
      type: keywordsform.value.type,
      stutas: 1,
    })
    .then(async (r) => {
      if (r.code == 1) {
        htmlContent.value = "";
        lutianorderlisttotal.value = r.total;
        lutianorderlist.value = r.data;
        progressshow.value = false;
      } else {
        htmlContent.value = removeEscapedCharacters(r.data);
        setTimeout(() => {
          const regex = /\\"total\\":\s*(\d+)/;
          const match = r.data.match(regex);
          lutianorderlisttotal.value = parseFloat(match[1]);

          const logincard = htmlContainer.value.querySelector(".login-card");
          if (logincard != null) {
            ElMessage({
              message: "所选账号登录已过期，请重新登录",
              type: "warning",
            });
            htmlContent.value = "";
            getlutianorderloading.value = false;
          } else {
            let trids = [];
            if (keywordsform.value.type == 1) {
              let trs = htmlContainer.value.querySelectorAll(
                ".mybid-table tbody tr .col-user"
              );
              trs.forEach((item) => {
                trids.push(item.childNodes[0].data.replace(/\s/g, ""));
              });
            } else {
              let trs = htmlContainer.value.querySelectorAll(
                ".mybid-table tbody tr"
              );
              trs.forEach((item) => {
                let href =
                  item.querySelector(".bk12") == null
                    ? ""
                    : item.querySelector(".bk12").href;
                if (href == "") {
                  trids.push("");
                } else {
                  let match = href.match(/tno=(\d+)/);

                  if (match) {
                    trids.push(match[1]);
                  } else {
                    trids.push("");
                  }
                }
              });
            }

            if (trids.length > 0) {
              console.log(trids);
              progressshow.value = true;
              ordertrs.value = trids.length;
              recugetorderdetail(0, trids, 3);
            }
          }
        }, 100);
      }
    });
};
const orderListrowStyle = ({ row, rowIndex }) => {
  if (row.orderStutas == 1) {
    return { background: "#fff" };
  } else if (row.orderStutas == 2) {
    return { background: "#E6A23C" };
  } else if (row.orderStutas == 3) {
    return { background: "#67C23A" };
  } else if (row.orderStutas == 4) {
    return { background: "#909399" };
  }
};

const changeorderStutas = (row) => {
  let indexs = (lutianorderlistcurrentpage.value - 1) * 30 + row.index;
  console.log(indexs);
  ipc
    .invoke(ipcApiRoute.changeDBorder, {
      userId: activeuser.value.userId,
      accountId: keywordsform.value.accountid,
      type: keywordsform.value.type,
      index: indexs,
      data: JSON.stringify(row),
    })
    .then(async (r) => {
      console.log(r);
    });
};

onMounted(() => {
  activeuser.value = JSON.parse(localStorage.getItem("currentUserstr"));
  getaccount();
});
</script>
    
    <style scoped>
.orderlist {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.orderlist-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px 0;
  border-bottom: 1px solid #dcdfe6;
}
.orderlist-title {
  font-size: 16px;
  font-weight: bold;
}
.adduser-button {
  font-size: 12px;
}
.orderlist-content {
  padding: 10px 0;
  flex: 1;
}
.orderlist-footer {
  height: 40px;
  display: flex;
  justify-content: center;
}

.userbuttons {
  width: 100%;
  display: flex;
}

.other-orderdiv {
  display: flex;
  flex-direction: column;
  padding: 5px;
  font-size: 12px;
  width: 100%;
  /* border: 1px solid red;
      height: 80px; */
}

.other-orderdiv-text {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.addother-orderbuttons {
  width: 100%;
  height: 50px;
}
.addother-orderbuttons .el-button {
  width: 80%;
  height: 50px;
}
.addother-ordertest {
  width: 90%;
  border: 1px dashed #dcdfe6;
  border-radius: 5px;
  margin-left: 80px;
}
.othertest-content {
  padding: 10px 0;
}
.othertest-item {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.othertest-content-title {
  display: flex;
  justify-content: center;
  font-size: 15px;
  font-weight: bold;
}

.orderlist-expand {
  display: flex;
  flex-wrap: wrap;
  padding: 0 50px;
}
.orderlist-expand-item {
  width: 45%;
  display: flex;

  align-items: flex-start;
  /* border: ; */
}
.orderlist-expand-item:nth-child(even) {
  border-right: 1px solid #d4d7de;
  border-top: 1px solid #d4d7de;
}
.orderlist-expand-item:nth-child(odd) {
  border-right: 1px solid #d4d7de;
  border-left: 1px solid #d4d7de;
  border-top: 1px solid #d4d7de;
}
.orderlist-expand-item:nth-last-child(1),
.orderlist-expand-item:nth-last-child(2) {
  border-bottom: 1px solid #d4d7de;
}

/* border-right: 1px solid #D4D7DE; */
.orderlist-expand-item-text {
  display: flex;
  font-size: 13px;
  align-items: center;
  margin-left: 10px;
  margin-top: 1px;
  width: 65%;
  padding: 10px 10px;
}
.orderlist-expand-item-title {
  font-size: 13px;
  font-weight: bold;
  display: flex;
  width: 30%;
  height: 100%;
  border-right: 1px solid #e4e7ed;
  padding: 10px 10px;
}

.orderlist-expand-other {
  display: flex;
  flex-direction: column;
}
.expand-other-item {
  display: flex;
  align-items: center;
}

.expressnums {
  display: flex;
  align-items: flex-end;
  justify-content: start;
  width: 100%;
}
.expressnum-inputs {
  display: flex;
  flex-direction: column;
  width: 100%;
}
.expressnum-input {
  width: 100%;
  margin-bottom: 10px;
}
.addexpressnum-button {
  margin-left: 15px;
  margin-bottom: 10px;
}

.orderlist-button {
  display: flex;
  justify-content: center;
  padding: 15px 0;
}

.addexpressnum {
  display: flex;
  align-items: flex-start;
}
.addexpressnum-inputs {
  display: flex;
  flex-direction: column;
}

.orderlist-progress {
  display: flex;
  padding: 0 20px;
  width: 90%;
  align-items: center;
  font-size: 13px;
}
</style>
  
  <style>
.orderlist-keywords-form {
  display: flex;
  flex-wrap: wrap;
}
.orderlist-keywords-form .el-form-item {
  margin: 0 15px 0 0;
  padding: 8px 0;
}

.orderlist-keywords-form .el-form-item .el-form-item__label {
  font-size: 13px;
}

.orseruserid-select .el-select-dropdown__item {
  font-size: 13px;
}
.orseruserid-selectinput .el-select__wrapper {
  font-size: 13px;
}
.orderlisttabel .el-scrollbar__view {
  width: 100%;
}

.selectexport-content {
  display: flex;
  flex-direction: column;
}

.selectexport-content .selectexportmaps {
  display: flex;
  flex-wrap: wrap;
}
.selectexport-content .selectexportmaps .el-checkbox {
  width: 43%;
  margin: 10px 0;
  margin-right: 10px;
}

.matchingaddupload .el-upload-dragger {
  height: 100%;
}

.el-pagination button.el-pager {
  pointer-events: none;
  opacity: 0.5;
  cursor: not-allowed;
}

.paginationaddorderlist .el-pager li {
  opacity: 0.5; /* 降低透明度表示禁用 */
  cursor: not-allowed !important; /* 鼠标指针显示为不可用 */
  pointer-events: none !important; /* 禁止点击事件 */
}
.paginationaddorderlist .btn-prev,
.paginationaddorderlist .btn-next {
  padding: 0 8px;
  font-size: 13px;
}
</style>